package com.hudongwx.godoffood.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.myActivity.ChangePwdActivity;
import com.hudongwx.godoffood.activity.myActivity.CommunityMsgActivity;
import com.hudongwx.godoffood.activity.myActivity.MyCommunityActivity;
import com.hudongwx.godoffood.activity.myActivity.MyMore;
import com.hudongwx.godoffood.activity.myActivity.MyOrderActivity;
import com.hudongwx.godoffood.utils.API.API;
import com.hudongwx.godoffood.utils.MyApplication;
import com.hudongwx.godoffood.utils.MyJsonObject;
import com.hudongwx.godoffood.view.InputView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.http.app.ResponseParser;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;

/**
 * A simple {@link Fragment} subclass.
 */
@ContentView(R.layout.fragment_login)
public class LoginFragment extends Fragment {
    @ViewInject(R.id.login_user_input)
    private InputView userInput;
    @ViewInject(R.id.login_pwd_input)
    private InputView pwdInput;
    @ViewInject(R.id.login_view_see)
    private ImageView seePwdIv;
    private String TAG = "LoginFragment";
    private Handler handler;
    private JSONObject dataForUser;
    private Intent intent;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        pwdInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 10) {
                    //判断是否登陆成功
                    if (MyApplication.Uid.equals("1")) {

                        Log.i(TAG, "handleMessage: " + dataForUser);

                        intent = new Intent();
                        //设置返回结果
                        try {
                            intent.putExtra("icon", dataForUser.getString("iconurl"));
                            intent.putExtra("name", dataForUser.getString("NickName"));
                            intent.putExtra("couldId", dataForUser.getString("CloudID"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //是社区跳转过来的
                        if (getActivity().getIntent().getIntExtra("UIid", 0) == 101) {
                            Intent intent1 = new Intent(getActivity(), MyCommunityActivity.class);
                            try {
                                intent1.putExtra("icon", dataForUser.getString("iconurl"));
                                intent1.putExtra("name", dataForUser.getString("NickName"));
                                intent1.putExtra("couldId", dataForUser.getString("CloudID"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                           startActivity(intent1);
                            Log.i(TAG, "handleMessage: ====================================================");

                        } else if (getActivity().getIntent().getIntExtra("UIid", 0) == 102) {//订单
                            startActivity(new Intent(getActivity(), MyOrderActivity.class));

                        } else if (getActivity().getIntent().getIntExtra("UIid", 0) == 103) {//消息
                            startActivity(new Intent(getActivity(), CommunityMsgActivity.class));


                        } else if (getActivity().getIntent().getIntExtra("UIid", 0) == 104) {//修改密码
                            startActivity(new Intent(getActivity(), ChangePwdActivity.class));

                        } else if (getActivity().getIntent().getIntExtra("UIid", 0) == 105) {//更多
                            startActivity(new Intent(getActivity(), MyMore.class));

                        }
                            //返回主页面 更新数据 在上面的跳转之后还是会执行
                            getActivity().setResult(2, intent);
                            getActivity().finish();

                    } else {
                        Log.i(TAG, "handleMessage: " + dataForUser);
                        Toast.makeText(getActivity(), "账号或密码错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
        return view;
    }

    /**
     * 判断是否登陆成功
     *
     * @param view
     */
    @Event(R.id.login_btn)
    private void adjustLogin(View view) {
        if (!(TextUtils.isEmpty(userInput.getMytext()) && TextUtils.isEmpty(pwdInput.getMytext()))) {
            //登陆判断
            RequestParams requestParams = new RequestParams(API.loginUrl);
            requestParams.addBodyParameter("Action", "usePwd");
            requestParams.addBodyParameter("Md5Pwd", md5(pwdInput.getMytext()).toUpperCase());
            requestParams.addBodyParameter("Phone", userInput.getMytext());
            x.http().post(requestParams, new Callback.CommonCallback<MyJsonObject>() {
                @Override
                public void onSuccess(MyJsonObject result) {
                    try {
                        //拿到登陆成功的代码
                        MyApplication.Uid = result.getString("Status");
                        //给全局变量赋值
                        String in = MyApplication.Uid;
                        Log.i(TAG, "onSuccess: " + in);
                        dataForUser = result.getJSONObject("Data");
                        //存入内存
                        MyApplication.storage(MyApplication.Uid);
                        Log.i(TAG, "onSuccess:dataForUser4 " + dataForUser);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.i(TAG, "onError: ");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    Log.i(TAG, "onCancelled: ");
                }

                @Override
                public void onFinished() {
                    //通知handler接收信息
                    handler.sendEmptyMessage(10);
                }
            });

        } else {
            Toast.makeText(getActivity(), "账号或密码不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 是否看见密码
     *
     * @param view
     */
    @Event(R.id.login_view_see)
    private void lookPwd(View view) {
        if (pwdInput.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {//明文 如果能看到
            //再次点击  设置成密码看不见  图片闭上眼睛
            pwdInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            seePwdIv.setSelected(false);
        } else {
            // 设置成密码看得见  初始的时候进来，设置为可见，图片页睁开眼
            pwdInput.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            seePwdIv.setSelected(true);
        }
    }

    //设置自动登陆
    @Event(R.id.login_view_auto)
    private void autoLogin(View view) {
        view.setSelected(!view.isSelected());
    }

    //密码的MD5加密
    public String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            Log.i(TAG, "md5: " + result.toUpperCase());
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    //第三方登陆
    @Event(R.id.login_view_qq)
    private void otherLogin(View view) {
        ShareSDK.initSDK(getActivity());
        Platform QQPlatform= ShareSDK.getPlatform(QQ.NAME);
        //因为登录成功以后，就不会再次登录，为了演示，我在登录之前，移除授权
        QQPlatform.removeAccount(true);

        QQPlatform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, final HashMap<String, Object> hashMap) {
                Log.i(TAG, "onComplete: "+hashMap.toString());
                //在ui线程提示
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(),"登录成功："+hashMap.get("nickname"),Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                    }
                });
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.i(TAG, "onError: "+throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.i(TAG, "onCancel: "+platform.getName());

            }
        });
//authorize与showUser单独调用一个即可
//        QQPlatform.authorize();//单独授权,OnComplete返回的hashmap是空的
        QQPlatform.showUser(null);//授权并获取用户信息
//移除授权
//weibo.removeAccount(true);
    }
    @Event(R.id.login_view_weibo)
    private void toWeibo(View view){
        Toast.makeText(getActivity(),"你未安装新浪微博",Toast.LENGTH_SHORT).show();
    }
}
